<template>
  <div class="page">
    <div class="detail">
      <div class="detail-cnt">
        <div class="top">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item style="font-size:18px;" :to="{ path: '/qa' }">互动问答</el-breadcrumb-item>
            <el-breadcrumb-item style="font-size:18px;">话题详情</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="content">
          <div class="topicContent">
            <h3 class="title">{{ post_title }}</h3>
            <div class="content" v-html="post_content"></div>
          </div>
          <div class="replyNumber">
            <div style="margin-top:30px;border-bottom: 1.5px solid #e0e0e0; height:2px;"></div>
            <div 
              class="reply_list" 
              v-for="(item, index) in commentList" 
              :key="index"
              :class="{'own-comment': item.username === NowUsername}"  
            >
              <div class="reply_header">
                <img :src="item.img_url" alt="User Avatar" class="avatar" />
                <p class="username">{{ item.username }}:</p>
              </div>
              <div class="reply_content">
                <p class="comment_content">{{ item.comment_content }}</p>
                 
                <div style="display: flex;
                    justify-content: flex-end;
                    gap: 10px;
                    align-items: flex-end;">
                  <span 
                    v-if="item.username === NowUsername" 
                    @click="deletePost(item.comment_id)" 
                    class="delete-btn"
                  >
                    删除
                  </span>
                  <label class="update_time">{{ item.update_time }}</label>
              </div>
              </div>
            </div>
          </div>
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :disabled="disabled"
              :background="background"
              layout="total, sizes, prev, pager, next, jumper"
              :total="data_cnt"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
          <div class="reply">
            <el-input
              type="textarea"
              v-model="newComment"
              placeholder="请输入你的评论"
              rows="4"
              class="comment-input"
            ></el-input>
            <div style="display: flex; justify-content: flex-end; height: 50px; align-items: center; padding: 40px;">
               <el-button type="primary" @click="submitComment" style="margin=10px;">发表回复</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="public">
        <img :src="img_url" />
        <p>发帖人</p>
        <p>
          <span>{{ username }}</span>
          <span>{{ userType }}</span>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage,ElMessageBox } from 'element-plus';
import { getDetail } from '@/services/topic';
import api from '@/services/api';

const route = useRoute();

// 基本数据
const post_id = ref(route.query.id);
const currentPage = ref(1);
const pageSize = ref(4);
const background = ref(false);
const disabled = ref(false);
const data_cnt = ref(0);

// 评论相关
const newComment = ref('');
const commentList = ref([]);

// 话题信息
const post_title = ref('');
const post_content = ref('');
const publisher_id = ref('');
const img_url = ref('');
const username = ref('');
const NowUsername = ref(localStorage.getItem('username'));
const user_type = ref('');
const userType = ref('');

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getReply();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getReply();
};

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning("评论内容不能为空");
    return;
  }

  const user_id = localStorage.getItem("id");

  try {
    const response = await api.post('/youxich/home/comment', {
      post_id: parseInt(post_id.value),
      user_id: parseInt(user_id),
      comment_content: newComment.value
    });

    if (response.data.status === 0) {
      // 后端判定为违规词
      ElMessage.warning(response.data.msg || "评论失败");
    } else {
      ElMessage.success("评论成功！");
      newComment.value = '';
      commentList.value = [];
      getReply();
    }

  } catch (err) {
    ElMessage.error("评论失败：" + (err.response?.data?.msg || err.message));
  }
};

// 获取话题详情和评论
const getReply = async () => {
  try {
    const res = await getDetail(post_id.value, currentPage.value, pageSize.value);
    const data = res.data.data;

    publisher_id.value = data.publisher_id;
    img_url.value = data.img_url;
    username.value = data.username;
    user_type.value = data.user_type;
    post_title.value = data.post_title;
    post_content.value = data.post_content;
    data_cnt.value = data.data_cnt;

    userType.value = user_type.value === 'teacher' ? '老师'
      : user_type.value === 'student' ? '学生'
      : '管理员';

    commentList.value = data.commentList.map(item => ({
      comment_id: item.comment_id,  // Add comment_id for deletion
      user_id: item.user_id,
      username: item.username,
      img_url: item.img_url,
      comment_content: item.comment_content,
      update_time: item.update_time
    }));
  } catch (err) {
    ElMessage.error("话题详情获取失败：" + err);
  }
};

const deletePost = async (commentId) => {
   try {
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？此操作不可撤销。',
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    const response = await api.delete(`/youxich/home/comment/${commentId}`);
    if (response.data.status === 1) {
      ElMessage.success("删除成功！");
      getReply();
    } else {
      ElMessage.warning(response.data.msg || "删除失败");
    }
  } catch (err) {
    ElMessage.error("删除失败：" + (err.response?.data?.msg || err.message));
  }
};

// 初始化
onMounted(() => {
  getReply();
});
</script>

<style scoped>
.own-comment {
  background-color: #f1f8ff8c;
}

.delete-btn {
  cursor: pointer;
    font-size: 14px;
  color: #999;
  margin-left: 10px;
}
.delete-btn:hover{
  text-decoration: underline;
}
.detail{
  margin-top: 10px;
  margin-left: 15%;
  background: rgba(242, 242, 242);
  height:auto;
  /*margin-top: 30px;*/
  display: flex;
  justify-content: space-around;
  /*justify-content: center;*/
  padding-bottom: 30px;
  min-height: 80vh;
}
.detail-cnt{
  width:800px;
  margin-right: 40px;
  /*padding:20px;*/
  margin-top:30px;
  background: #FFFFFF;
  border-radius: 10px;
}
.top{
  padding:30px;
  margin-bottom: 30px;
  font-size:20px;
}

.topicContent {
  border: 1px solid #CACCC7;
  background: #F7F7F7;
  height: auto;
  max-width: 90%;
  margin: 0 auto;
  border-radius: 10px;
  box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.1);
}

.topicContent .title {
  padding: 15px;
  margin-left: 20px;
  font-weight: normal;
  font-size: 18px;
}

.topicContent .content {
  padding: 15px;
  margin-left: 20px;
  font-size: 15px;

}

.replyNumber {
  width: 100%;
  max-width: 87%;
  margin: 0 auto;
}

.reply_list {
  border-bottom: 1.5px solid #e0e0e0;
  padding: 20px;
}

.reply_header {
  display: flex;
  align-items: center;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  font-weight: bold;
  font-size: 18px;
}

.reply_content {
  margin-top: 5px;
}

.comment_content {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
  padding-left:80px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制显示两行 */
  -webkit-box-orient: vertical;
}

.update_time {
  font-size: 14px;
  color: #999;
  margin-top: 5px;
  display: flex;
  justify-content: flex-end;
}


.public{
  margin-right: 200px;
  width: 200px;
  height:180px;
  margin-top:30px;
  background: #FFFFFF;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding:10px;
  padding-bottom: 20px;

}
.public img{
  border-radius: 50%;
  width:80px;
  height: 80px;
  border:1px solid #FED218;

}
.public p{
  font-size:16px;
  font-weight: bold;
}
.public p span{
  font-weight: normal;
}
.public p span:nth-child(2){
  width:30px;
  padding:4px;
  margin-left:10px;
  color:#fff;
  border-radius: 5px;
  background: #0B57D0;
}

.demo-pagination-block{
  margin-left:50px;
}
.page{
    padding:10px;
    background: rgba(242,242,242);
    display: flex;
    justify-content: center;

}
.comment-input {
  width: 90%;
  margin-left: 5%;
}
</style>